<template>
	<navBar title="备忘录"></navBar>

	<!-- 统计卡片 -->
	<view class="stats-card" :style="{ backgroundColor: themeColors.cardColor }">
		<view class="stat-item">
			<view class="stat-number" :style="{ color: themeColors.accentColor }">{{ stats.pending }}</view>
			<view class="stat-label" :style="{ color: themeColors.subTextColor }">待完成</view>
		</view>
		<view class="stat-divider" :style="{ backgroundColor: themeColors.dividerColor }"></view>
		<view class="stat-item">
			<view class="stat-number" :style="{ color: themeColors.successColor }">{{ stats.completed }}</view>
			<view class="stat-label" :style="{ color: themeColors.subTextColor }">已完成</view>
		</view>
	</view>

	<!-- 备忘录列表 -->
	<view class="memo-container">
		<view class="section-title" :style="{ color: themeColors.subTextColor }">
			<view class="title-left">
				<view class="calendar-btn" @click="showCalendar = true" :style="{ color: themeColors.accentColor }">
					<up-icon name="calendar" size="28"></up-icon>
				</view>
				<view class="date" :style="{ color: themeColors.subTextColor }">{{ displayDate }}</view>
			</view>

			<view class="title-middle" v-if="sortStyle">
				<view class="clock-btn" @click="toImporSort" style="{ color: themeColors.accentColor }">
					<up-icon name="clock" size="28"></up-icon>
				</view>
				<view class="sort" :style="{ color: themeColors.subTextColor }">时间排序</view>
			</view>
			<view class="title-middle" v-else>
				<view class="clock-btn" @click="toTimeSort" style="{ color: themeColors.accentColor }">
					<up-icon name="star" size="28"></up-icon>
				</view>
				<view class="sort" :style="{ color: themeColors.subTextColor }">重要排序</view>
			</view>

			<view class="title-right">
				<view v-if="isLocation" :style="{ color: themeColors.subTextColor }">{{ open }}</view>
				<view v-if="!isLocation" :style="{ color: themeColors.subTextColor }">{{ close }}</view>
				<up-switch :model-value="isLocation" @change="changeIsLocation" :activeColor="themeColors.accentColor"
					inactiveColor="#e5e5e5"></up-switch>
			</view>
		</view>

		<u-calendar :show="showCalendar" title="选择日期" :min-date="minDate" :formatter="formatter"
			@close="showCalendar = false" @confirm="handleDateConfirm"></u-calendar>

		<up-swipe-action>
			<view class="swipe-action-item" v-for="(item, i) in filteredMemoList" :key="item[0]">
				<up-swipe-action-item :options="options" :name="item[0]"
					@click="(btn) => handleSwipeAction(btn, item[0])">
					<view class="memo-card" :style="{ backgroundColor: themeColors.cardColor }">
						<view class="memo-top">
							<!-- 显示日期 -->
							<view class="memo-date" :style="{ color: themeColors.subTextColor }" currentEditIndex="i">
								{{ item[2] }}
							</view>
							<view class="memo-impor"><u-rate activeIcon="star-fill" inactiveIcon="star"
									:active-color="themeColors.accentColor" :count="imporCount" :modelValue="item[4]"
									@change="(value) => setMemoImpor(item[0], value+1)"></u-rate>
							</view>
						</view>
						<view class="memo-content" :class="{'completed': item[3] === '1', 'pending': item[3] === '0'}">
							<text class="memo-text" :style="{ 
									color: item[3] === '1' ? themeColors.subTextColor : themeColors.textColor,
								}">
								{{ item[0] }}
							</text>
						</view>
					</view>
				</up-swipe-action-item>
			</view>
		</up-swipe-action>

		<!-- 空状态提示 -->
		<view v-if="filteredMemoList.length === 0" class="empty-state" :style="{ color: themeColors.subTextColor }">
			<u-icon name="file-text" size="80"></u-icon>
			<text class="empty-text">暂无备忘录</text>
			<text class="empty-subtext">添加你的第一条备忘录吧~</text>
		</view>
	</view>

	<refreshButton></refreshButton>
	<tabBar></tabBar>
</template>

<script>
	import {
		useMemoStore
	} from '@/stores/memoStore'
	import {
		filterMemoList
	} from '@/stores/filterMemoList'
	import {
		themeColor
	} from '@/stores/themeColor'
	import {
		locationTracker
	} from '@/utils/getLocation'
	import {
		userInfo
	} from '../../stores/userInfo'

	export default {
		data() {
			return {
				// 滑动操作选项
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#e74c3c'
					},
					action: 'delete'
				}, {
					text: '完成',
					style: {
						backgroundColor: '#2ecc71'
					},
					action: 'complete'
				}],

				// 重要性最大值
				imporCount: 5,

				// 日历控制变量（用于显示/隐藏u-calendar）
				showCalendar: false,
				// 最小可选日期
				minDate: '2025-09-15',

				// 用于setCurrentDate使用date对象的函数
				selectedDate: new Date(),
				// 用于显示，获取日历选择
				displayDate: '',

				// 控制时间排序或重要性排序 true代表时间排序
				sortStyle: true,

				// 设置重要性防抖
				importAntiShake: false,

				// 是否开启定位提醒功能
				isLocation: false,
				// 文字告知用户当前定位功能状态
				open: '定位提醒已开启',
				close: '定位提醒已关闭'
			};
		},

		computed: {
			// 当前主题颜色
			themeColors() {
				return themeColor().themes[themeColor().currentThemeIndex]
			},

			// 统计数据
			stats() {
				const pending = this.filteredMemoList.filter(item => item[3] === '0').length
				const completed = this.filteredMemoList.filter(item => item[3] === '1').length
				return {
					pending,
					completed
				}
			},

			// 全部备忘录数据
			memoList() {
				return useMemoStore().memoList
			},
			// 筛选日期后的数据
			filteredMemoList() {
				return filterMemoList().filteredMemoList
			},

			// 提取备忘录中所有存在的日期（去重，格式：YYYY-MM-DD）
			memoDates() {
				const allDates = this.memoList.map(item => {
					// 从 endTime（如 2025-09-25 12:00:00）中截取日期部分
					return item[2].split(' ')[0];
				})
				// 去重，避免同一日期重复标记小红点
				return [...new Set(allDates)]
			}
		},

		created() {
			// 刚创立时先获取一次数据
			useMemoStore().getMemoList()

			this.displayDate = '全部'
		},

		methods: {
			formatter(day) {
				// 1. 将日历当前日期（day.date）格式化为 YYYY-MM-DD（与备忘录日期匹配）
				const year = day.date.getFullYear();
				const month = String(day.date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，补0成两位数
				const date = String(day.date.getDate()).padStart(2, '0'); // 日期补0成两位数
				const currentDateStr = `${year}-${month}-${date}`;

				// 2. 对比当前日期是否在备忘录日期数组中，是则添加小红点样式
				if (this.memoDates.includes(currentDateStr)) {
					day.bottomInfo = '有日程'
					day.dot = true
				}
				return day
			},

			// 设置当前日期显示
			setCurrentDate() {
				this.selectedDate = new Date(this.displayDate)
				const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				this.displayDate =
					`${this.selectedDate.getMonth() + 1}月${this.selectedDate.getDate()}日 ${weekDays[this.selectedDate.getDay()]}`;
			},

			// 处理日历选择
			handleDateConfirm(e) {
				// console.log(e)
				this.displayDate = e[0]
				filterMemoList().setFilterDate(this.displayDate)
				this.setCurrentDate()
			},

			// 切换至重要性排序
			async toImporSort() {
				await useMemoStore().getMemoListImpor()
				this.sortStyle = false
			},
			// 切换至时间排序
			async toTimeSort() {
				await useMemoStore().getMemoList()
				this.sortStyle = true
			},

			// 处理滑块点击事件
			async handleSwipeAction(btn, name) {
				// console.log(btn.index)
				// console.log(name)

				const btnIndex = btn.index

				// 根据action标识分发到不同的处理函数
				switch (btnIndex) {
					case 0:
						await this.deleteMemoItem(name);
						break;
					case 1:
						await this.changeMemoItem(name);
						break;
				}
			},
			async deleteMemoItem(text) {
				const res = await useMemoStore().deleteMemoItem(text)
				if (this.sortStyle === true) {
					await useMemoStore().getMemoList()
				} else {
					await useMemoStore().getMemoListImpor()
				}
			},
			async changeMemoItem(text) {
				const res = await useMemoStore().changeMemoItem(text)
				if (this.sortStyle === true) {
					await useMemoStore().getMemoList()
				} else {
					await useMemoStore().getMemoListImpor()
				}
			},

			// 设置备忘录重要性
			async setMemoImpor(text, number) {
				if (this.importAntiShake) return
				else {
					this.importAntiShake = true
				}
				const res = await useMemoStore().setMemoImpor(text, number)
				console.log('触发setMemoImpor函数', text, number)
				if (this.sortStyle === true) {
					await useMemoStore().getMemoList()
				} else {
					await useMemoStore().getMemoListImpor()
				}
				this.importAntiShake = false
			},

			// 处理 开启/关闭 定位提醒
			changeIsLocation() {
				if (this.isLocation) {
					locationTracker.stopTracking()
				} else {
					locationTracker.startTracking((res) => {
						console.log("外部引用:", res)
					})
				}

				this.isLocation = !this.isLocation
			}
		}
	}
</script>

<style lang="scss">
	/* 原有样式完全保留，修复重复的.section-title样式 */
	page {
		background-color: v-bind('themeColors.bgColor');
		min-height: 100%;
	}

	// 统计卡片样式
	.stats-card {
		margin: 0 30rpx 30rpx;
		border-radius: 16rpx;
		padding: 25rpx;
		display: flex;
		justify-content: space-around;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.stat-item {
		flex: 1;
		text-align: center;
		padding: 10rpx 0;
	}

	.stat-number {
		font-size: 40rpx;
		font-weight: 700;
		margin-bottom: 5rpx;
	}

	.stat-label {
		font-size: 26rpx;
	}

	.stat-divider {
		width: 1rpx;
		height: 60rpx;
		align-self: center;
	}

	// 备忘录容器样式
	.memo-container {
		padding: 0 30rpx 120rpx;
	}

	// 日期显示+日历按钮 容器
	.section-title {
		font-size: 28rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.title-left {
			display: flex;
			align-items: center;
			gap: 5rpx; // 按钮和日期之间的间距

			// 日历按钮样式
			.calendar-btn {
				padding: 5rpx;
				border-radius: 8rpx;
				transition: background-color 0.2s;

				// 点击反馈
				&:active {
					background-color: rgba(0, 0, 0, 0.05);
				}
			}

			.date {
				font-size: 24rpx;
			}
		}

		.title-middle {
			display: flex;
			align-items: center;
			gap: 5rpx;

			.clock-btn {
				padding: 5rpx;
				border-radius: 8rpx;
				transition: background-color 0.2s;

				// 点击反馈
				&:active {
					background-color: rgba(0, 0, 0, 0.05);
				}
			}

			.sort {
				font-size: 24rpx;
			}
		}

		.title-right {
			display: flex;
			align-items: center;
			gap: 5rpx;
		}
	}

	// 滑动项样式
	.swipe-action-item {
		margin-bottom: 20rpx;
	}

	// 备忘录卡片样式
	.memo-card {
		border-radius: 16rpx;
		padding: 25rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.memo-top {
		display: flex;

		// 显示日期区域
		.memo-date {
			flex: 1;
			font-size: 24rpx;
			margin-bottom: 15rpx;
			padding-left: 40rpx;
		}

		// 显示重要性区域
		.memo-impor {
			margin-bottom: 15rpx;
		}
	}

	// 备忘录内容容器
	.memo-content {
		display: flex;
		align-items: center;
		min-height: 60rpx;
		padding: 10rpx 0;
		transition: all 0.2s ease; // 状态切换时添加过渡动画，更流畅
	}

	// 待办状态样式（works[i] === '0'）
	.pending {

		// 左侧添加主题色小竖线，突出待办
		&::before {
			content: '';
			width: 8rpx;
			height: 28rpx;
			border-radius: 4rpx;
			background-color: v-bind('themeColors.accentColor'); // 关联主题强调色
		}
	}

	// 已完成状态样式（works[i] === '1'）
	.completed {
		opacity: 0.8; // 整体降低透明度，视觉上“弱化”已完成事项

		// 左侧添加主题次要色小竖线，区分待办
		&::before {
			content: '';
			width: 8rpx;
			height: 28rpx;
			border-radius: 4rpx;
			background-color: v-bind('themeColors.subTextColor'); // 关联主题次要文本色
		}

		// 已完成文本添加删除线
		.memo-text {
			text-decoration: line-through;
			text-decoration-color: v-bind('themeColors.subTextColor'); // 删除线颜色匹配次要色
			text-decoration-thickness: 2rpx; // 控制删除线粗细，避免过于突兀
		}
	}

	// 备忘录文本通用样式（无需重复写颜色判断，已在template中绑定）
	.memo-text {
		font-size: 28rpx;
		margin-left: 15rpx; // 与左侧小竖线保持间距
		flex: 1;
		line-height: 1.5; // 优化多行文本可读性
		padding: 5rpx 0; // 增加文本上下内边距，点击区域更友好
	}

	// 空状态样式
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}

	.empty-text {
		font-size: 30rpx;
		margin: 30rpx 0 10rpx;
	}

	.empty-subtext {
		font-size: 24rpx;
		opacity: 0.8;
	}
</style>